package top.byfree.jbyan.saber.dao

import org.ktorm.dsl.*
import org.springframework.stereotype.Component
import top.byfree.jbyan.saber.bean.*
import top.byfree.jbyan.saber.bean.dto.FilterRoleDto
import top.byfree.jbyan.saber.bean.pojo.Role
import top.byfree.jbyan.saber.bean.vo.permVoCol
import top.byfree.jbyan.saber.common.BaseDao
import top.byfree.jbyan.saber.common.coverOrderBy

/**
 * 角色数据处理层
 *
 * @author jbyan
 * @since 21/3/2024
 */
@Component
open class RoleDao : BaseDao<Role, Roles>(Roles) {

    /* 条件过滤角色信息 */
    fun filter(filterRoleDto: FilterRoleDto): Query {
        val (roleName, roleKey, status, gmtCreateStart, gmtCreateEnd, createBy, modifyBy, orderBy) = filterRoleDto
        val query = database.from(Roles)
            .select()
            .whereWithConditions { cl ->
                cl += Roles.isDelete eq IS_DELETE_NO
                if (!roleName.isNullOrBlank()) {
                    cl += Roles.roleName like "%$roleName%"
                }
                if (!roleKey.isNullOrBlank()) {
                    cl += Roles.roleKey like "%$roleKey%"
                }
                status?.let {
                    cl += Roles.status eq it
                }
                gmtCreateStart?.let {
                    cl += Roles.gmtCreate gte it
                }
                gmtCreateEnd?.let {
                    cl += Roles.gmtCreate lte it
                }
                if (!createBy.isNullOrBlank()) {
                    cl += Roles.createBy like "%$createBy%"
                }
                if (!modifyBy.isNullOrBlank()) {
                    cl += Roles.modifyBy like "%$modifyBy%"
                }
            }

        val coverOrderBy = Roles.coverOrderBy(orderBy)
        // 添加排序
        return coverOrderBy?.let {
            query.orderBy(coverOrderBy)
        } ?: query
    }

    /* 根据角色编号获取角色下所有权限信息 */
    fun getPermList(roleId: String) =
        database.from(RolePerms)
            .leftJoin(Perms, on = Perms.permId eq RolePerms.permId)
            .select(permVoCol)
            .where {
                (Perms.isDelete eq IS_DELETE_NO) and
                        (Perms.status eq PERM_STATUS_NORMAL) and
                        (RolePerms.roleId eq roleId)
            }.map(Perms::createEntity)

}